# SPDX-License-Identifier: MIT
"""State management helpers for pmake."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Iterable, Set


STATE_DIR_NAME = "state"
DISABLED_FILE = "disabled.json"


def state_dir(build_dir: Path) -> Path:
    path = build_dir / STATE_DIR_NAME
    path.mkdir(parents=True, exist_ok=True)
    return path


def disabled_path(build_dir: Path) -> Path:
    return state_dir(build_dir) / DISABLED_FILE


def load_disabled(build_dir: Path) -> Set[str]:
    path = disabled_path(build_dir)
    if not path.exists():
        return set()
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"Failed to parse {path}: {exc}") from exc
    if not isinstance(data, list):
        raise RuntimeError(f"Invalid disabled state in {path}: expected list")
    return {str(item) for item in data}


def save_disabled(build_dir: Path, names: Iterable[str]) -> None:
    path = disabled_path(build_dir)
    path.write_text(
        json.dumps(sorted(set(str(name) for name in names)), indent=2) + "\n",
        encoding="utf-8",
    )
